﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace PServiceBus.Core.Runtime {
    public class ServiceProxy<TInterface> : ClientBase<TInterface>, IDisposable where TInterface : class {

        public delegate void ServiceProxyDelegate<T>(TInterface proxy);

        public ServiceProxy() : base(typeof(TInterface).ToString()) { }

        public ServiceProxy(string endpointConfigurationName) : base(endpointConfigurationName) { }

        public TInterface Proxy {
            get {
                return Channel;
            }

        }

        public static void Call(ServiceProxyDelegate<TInterface> proxyDelegate) {
            Call(proxyDelegate, typeof(TInterface).ToString());
        }

        public static void Call(ServiceProxyDelegate<TInterface> proxyDelegate, string endpointConfigurationName) {

            var channel = new ChannelFactory<TInterface>(endpointConfigurationName);
            try {
                proxyDelegate(channel.CreateChannel());
            } finally {
                if (channel.State == CommunicationState.Faulted) {
                    channel.Abort();
                } else {
                    try {
                        channel.Close();
                    } catch {
                        channel.Abort();
                    }
                }
            }
        }



        public void Dispose() {
            if (State == CommunicationState.Faulted) {
                Abort();
            } else {
                try {
                    Close();
                } catch {
                    Abort();
                }
            }
        }

    }
}
